package hmvictor.jpql;

import hmvictor.jpql.nodes.DriverChildrenFactory;
import hmvictor.jpql.nodes.DriverNode;
import hmvictor.jpql.nodes.FileChildrenFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.view.ListView;
import org.openide.util.Exceptions;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//hmvictor.jpql//Drivers//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "DriversTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "explorer", openAtStartup = true)
@ActionID(category = "Window", id = "hmvictor.jpql.DriversTopComponent")
@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_DriversAction",
        preferredID = "DriversTopComponent"
)
@Messages({
    "CTL_DriversAction=Drivers",
    "CTL_DriversTopComponent=Drivers",
    "HINT_DriversTopComponent=This is a Drivers window"
})
public final class DriversTopComponent extends TopComponent implements ExplorerManager.Provider {

    private static final String DRIVERS_FILE = "drivers.data";

    private final List<File> jarFiles = new LinkedList<>();
    
    private FileChildrenFactory fileChildrenFactory;
    
    private final ExplorerManager explorerManager = new ExplorerManager();

    public DriversTopComponent() {
        initComponents();
        setName(Bundle.CTL_DriversTopComponent());
        setToolTipText(Bundle.HINT_DriversTopComponent());
        listViewPanel.add(new ListView());
    }

    public List<URL> getJarUrls() throws MalformedURLException {
        List<URL> urls = new LinkedList<>();
        for (File file : jarFiles) {
            urls.add(Utilities.toURI(file).toURL());
        }
        return urls;
    }

    private void saveDriversList() throws FileNotFoundException {
        File file = new File(AppFiles.getAndCreateConfigDir(), DRIVERS_FILE);
        try (PrintWriter writer = new PrintWriter(file)) {
            jarFiles.forEach((f) -> {
                writer.println(f.getAbsolutePath());
            });
        }
    }

    private void loadDriversList() throws FileNotFoundException, IOException {
        File file = new File(AppFiles.getAndCreateConfigDir(), DRIVERS_FILE);
        if (file.exists() && file.isFile()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    jarFiles.add(new File(line));
                }
            }
        }
    }

    public void removeDriver(File file) {
        jarFiles.remove(file);
        fileChildrenFactory.refreshChildren();
        try {
            saveDriversList();
        } catch (FileNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    
    public void addDriver(File selectedFile) {
        jarFiles.add(selectedFile);
        fileChildrenFactory.refreshChildren();
        try {
            saveDriversList();
        } catch (FileNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileChooser = new javax.swing.JFileChooser();
        listViewPanel = new javax.swing.JPanel();

        fileChooser.setFileFilter(new FileNameExtensionFilter("Jar file", "jar"));

        listViewPanel.setLayout(new java.awt.BorderLayout());

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(listViewPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 364, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(listViewPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 322, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JPanel listViewPanel;
    // End of variables declaration//GEN-END:variables
    
    @Override
    public void componentOpened() {
        try {
            loadDriversList();
            fileChildrenFactory = new DriverChildrenFactory(jarFiles);
            explorerManager.setRootContext(new DriverNode(fileChildrenFactory));
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    @Override
    public ExplorerManager getExplorerManager() {
        return explorerManager;
    }

}
